import java.util.ArrayList;
import java.util.Date;

/**
 * PageViewCounter
 *
 * @author 28189
 * @since 2024/12/12 17:02
 */
public class PageViewCounter {
    private ArrayList<Page> pages = new ArrayList<>();


    public PageViewCounter() {
        pages.add(new Page("https://www.bing.com/"));
        pages.add(new Page("https://www.sogou.com/"));
        pages.add(new Page("https://www.baidu.com/"));
    }
    //记录访问
    public void recordPageView(String url){
        Page pageToVisit = getPage(url);
        for (int i = 0; i < pages.size(); i++) {
            Page page = pages.get(i);
            if (url.equals(page.getUrl())) {
                pageToVisit = page;
                break;
            }
        }
        if (pageToVisit==null){
            pageToVisit=new Page(url);
            pages.add(pageToVisit);
        }
        pageToVisit.setViewCount(pageToVisit.getViewCount() + 1);
        pageToVisit.setLastViewed(new Date());
    }
    //页面访问对象查找
    private Page getPage(String url) {
        for (Page page : pages) {
            String pageUrl = page.getUrl();
            if (url.equals(page.getUrl())) {
                return page;
            }
        }
        return null;
    }
    //显示访问排行
    public void showTopViewedPages() {
        pages.sort((p1, p2) -> p2.getViewCount() - p1.getViewCount());
        for (int i = 0; i < pages.size(); i++)
            System.out.println((i + 1) + ". " + pages.get(i).getUrl() + " - " + pages.get(i).getViewCount() + " views");
    }
    //统计总访问量
    public int getTotalViewCount() {
        int total = 0;
        for (Page page : pages) {
            total += page.getViewCount();
        }
        return total;
    }
    //平均访问量
    public double getAverageViewCount() {
        return (double) getTotalViewCount() / pages.size();
    }
    //最后访问时间
    public Date getLastAccessTime(String url) {
        Page page = getPage(url);
        if (page != null) {
            return page.getLastViewed();
        }
        return null;
    }
    //清空访问
    public void clearAllPageViews() {
        pages.clear();
    }
}
